<template>
  <el-form ref="loginForm" :model="form" :rules="rules" label-width="0" size="large" @keyup.enter="login">
    <el-form-item prop="user">
      <el-input v-model="form.user" prefix-icon="el-icon-user" clearable :placeholder="$t('login.userPlaceholder')">
<!--        <template #append>-->
<!--          <el-select v-model="userType" style="width: 130px;">-->
<!--            <el-option :label="$t('login.admin')" value="admin"></el-option>-->
<!--            <el-option :label="$t('login.user')" value="user"></el-option>-->
<!--          </el-select>-->
<!--        </template>-->
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="form.password" prefix-icon="el-icon-lock" clearable show-password :placeholder="$t('login.PWPlaceholder')"></el-input>
    </el-form-item>
<!--    验证码-->
    <el-form-item>
      <div class="boxCode">
        <el-input v-model="form.captcha" prefix-icon="el-icon-CircleCheck" clearable placeholder="请输入验证码" class="plinpnt"></el-input>
        <el-image :src="captcha.url" @click="getCodeApi" class="code"></el-image>
      </div>
    </el-form-item>

    <el-form-item style="margin-bottom: 10px;">
      <el-col :span="12">
        <el-checkbox :label="$t('login.rememberMe')" v-model="form.autologin"></el-checkbox>
      </el-col>
      <el-col :span="12" class="login-forgot">
        <router-link to="/reset_password">{{ $t('login.forgetPassword') }}？</router-link>
      </el-col>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" style="width: 100%;" :loading="islogin" round @click="login">{{ $t('login.signIn') }}</el-button>
    </el-form-item>
<!--    <div class="login-reg">-->
<!--      {{$t('login.noAccount')}} <router-link to="/user_register">{{$t('login.createAccount')}}</router-link>-->
<!--    </div>-->
  </el-form>
</template>

<script>

export default {
  data() {
    return {
      userType: 'admin',
      form: {
        user: "admin",
        password: "abc123456",
        captcha: "",
        autologin: false
      },
      rules: {
        user: [
          {required: true, message: this.$t('login.userError'), trigger: 'blur'}
        ],
        password: [
          {required: true, message: this.$t('login.PWError'), trigger: 'blur'}
        ]
      },
      captcha: {
        key: new Date().getTime(),
        url: ''
      },
      islogin: false,
      rolePerm:[]
    }
  },
  watch:{
    userType(val){
      if(val == 'admin'){
        this.form.user = 'admin'
        this.form.password = 'admin'
      }else if(val == 'user'){
        this.form.user = 'user'
        this.form.password = 'user'
      }
    }
  },
  created() {
    this.getCodeApi()
  },
  methods: {
    async getCodeApi(){
      this.captcha.key = new Date().getTime()
      const res = await this.$API.auth.imageCaptcha.get({key: this.captcha.key})
      this.captcha.url =
        'data:image/png;base64,' +
        btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''));
    },
    async login(){
      var validate = await this.$refs.loginForm.validate().catch(()=>{})
      if(!validate){ return false }

      this.islogin = true
      var data = {
        username: this.$TOOL.crypto.AES.encrypt(this.form.user, 'bGvnMc62sh5RV6zP', {iv: '1eZ43DLcYtV2xb3Y', mode: 'CBC'}),
        password: this.$TOOL.crypto.AES.encrypt(this.form.password, 'bGvnMc62sh5RV6zP', {iv: '1eZ43DLcYtV2xb3Y', mode: 'CBC'}),
        key: this.captcha.key,
        captcha: this.form.captcha
      }

      //获取token
      try{
        let user = await this.$API.auth.login.post(data)
        this.$TOOL.cookie.set("TOKEN", user.data, {
          expires: this.form.autologin? 24*60*60 : 0
        })

        // 获取个人信息
        let userInfo = await this.$API.system.menu.list.get()
        this.$TOOL.data.set("USER_INFO", userInfo.data.userInfo)
        this.$TOOL.data.set("USER_ROLES", userInfo.data.roles)
        this.$TOOL.data.set("USER_CRT_ROLE", userInfo.data.roles[0])
        this.rolePerm = userInfo.data.roles[0].rolePerm
        // 获取菜单
        let menu = await this.$API.system.menu.myMenus.get(this.rolePerm)
        if(menu.data.length==0){
          this.islogin = false
          this.$alert("当前用户无任何菜单权限，请联系系统管理员", "无权限访问", {
            type: 'error',
            center: true
          })
          return false
        }

        this.$TOOL.data.set("MENU", menu.data)
        this.$TOOL.data.set("PERMISSIONS", userInfo.data.permissions)

        this.$router.replace({
          path: '/dashboard'
        })
        this.$message.success("Login Success 登录成功")
        this.islogin = false
      } catch (error){
        this.$notify.error({
          title: "请求错误",
          message: error
        });
        this.islogin = false
      }
    }
  },
}

</script>

<style>
.boxCode{
  display: flex;
  align-items: center;
  width: 100%;
}
.code{
  margin-left: 10px;
  height: 40px;
  cursor: pointer;
}

</style>
